<!--  -->
<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{path: '/home'}">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="dialogVisiable = true">添加分类</el-button>
        </el-col>
      </el-row>
      <tree-table
        class="tb-cate"
        index-text="#"
        show-index
        stripe
        border
        :data="cateList"
        :columns="columns"
        :expand-type="false"
        :selection-type="false"
      >
        <template slot="isok" slot-scope="scope">
          <i class="el-icon-success" v-if="scope.row.effective" style="color: lightGreen"></i>
          <i class="el-icon-error" v-else style="color: red"></i>
        </template>
        <template slot="level" scope="scope">
          <el-tag type="primary" effect="plain" size="mini" v-if="scope.row.level === 1">一级</el-tag>
          <el-tag type="success" effect="plain" size="mini" v-else-if="scope.row.level === 2">二级</el-tag>
          <el-tag type="warning" effect="plain" size="mini" v-else>三级</el-tag>
        </template>
        <template slot="opt" scope="scope">
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="mini"
            @click="showUpdateDialog(scope.row)"
          >编辑</el-button>
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="deleteCate(scope.row.id, scope.row.level)"
          >删除</el-button>
        </template>
      </tree-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="query.currentPage"
        :page-sizes="[5, 10, 20, 50, 100]"
        :page-size="query.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        hide-on-single-page
        :total="total"
      ></el-pagination>
    </el-card>
    <el-dialog
      :title="isEdit? '修改分类': '添加分类'"
      :visible.sync="dialogVisiable"
      :close-on-click-modal="false"
      @close="clearForm('form')"
      @open="handleOpen"
    >
      <el-form :model="form" :rules="rules" ref="form" label-position="left" label-width="100px" label-suffix=":">
        <el-form-item label="分类名称" prop="name" required >
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类" v-if="!isEdit">
          <el-cascader
            :options="cateListWithLevel"
            :props="propsWithLevel"
            placeholder="请选择父级分类"
            v-model="cates"
            clearable
          ></el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogVisiable = false">取消</el-button>
        <el-button type="primary" @click="submitForm('form')">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      cateList: [],
      query: {
        currentPage: 1,
        pageSize: 5,
      },
      total: 0,
      columns: [
        { label: "分类名称", prop: "name" },
        {
          label: "是否有效",
          prop: "effective",
          type: "template",
          template: "isok",
        },
        {
          label: "分类等级",
          prop: "level",
          type: "template",
          template: "level",
        },
        {
          label: "操作",
          type: "template",
          template: "opt",
        },
      ],
      props: {
        expandType: false,
        selectionType: false,
      },
      dialogVisiable: false,
      cates: [],
      form: {
        id: null,
        name: "",
        level: 1,
        pid: 0,
        effective: true,
      },
      rules: {
        name: [{ required: true, message: "请输入分类名称", trigger: "blur" }],
      },
      cateListWithLevel: [],
      propsWithLevel: {
        // expandTrigger: 'hover',
        value: "id",
        label: "name",
        checkStrictly: true,
      },
    };
  },

  created() {
    this.getCateList();
  },
  computed: {
    isEdit() {
      return this.form.id !== null;
    },
  },
  methods: {
    getCateList() {
      this.$http.get("/category/page", { params: this.query }).then((resp) => {
        if (!resp.flag) {
          this.$message.warning("查询失败");
          return;
        }

        this.total = resp.data.total;
        this.cateList = resp.data.items;
        // console.log(resp);
      });
    },
    handleSizeChange(val) {
      this.query.pageSize = val;
      this.getCateList();
    },
    handleCurrentChange(val) {
      this.query.currentPage = val;
      this.getCateList();
    },
    getCateWithLevel(level) {
      this.$http
        .get("/category/level", {
          param: {
            level,
          },
        })
        .then((resp) => {
          if (!resp.flag) {
            this.$message.warning("查询失败");
            return;
          }
          // console.log(resp);
          this.cateListWithLevel = resp.data;
        });
    },
    clearForm(formName) {
      this.cates = [];
      this.form.id = null;
      this.form.name = "";
      this.form.pid = 0;
      this.form.level = 1;
      this.form.effective = true;
      this.cateListWithLevel = [];
      this.$refs[formName].clearValidate(this.form)
    },

    submitAdd() {
      // console.log("add");
      const len = this.cates.length;

      const param = { ...this.form };
      param.pid = len ? this.cates[len - 1] : 0;
      param.level = len + 1;
      this.$http.post("/category", param).then((resp) => {
        // console.log(resp);
        if (!resp.flag) {
          this.$message.warning(resp.message);
          return;
        }
        this.getCateList();
        this.dialogVisiable = false;
      });
    },
    showUpdateDialog(item) {
      this.form = { ...item };
      this.dialogVisiable = true;
    },
    submitUpdate() {
      // console.log("update");
      this.$http.put("/category", this.form).then((resp) => {
        if (!resp.flag) {
          this.$message.warning(resp.message);
          return;
        }
        this.getCateList();
        this.dialogVisiable = false;
      });
    },
    handleOpen() {
      // console.log("open");
      if (!this.isEdit) {
        this.getCateWithLevel(2);
      }
    },
    submitForm(formName) {
      // console.log("submit");
      this.$refs[formName].validate((valid) => {
        if (!valid) {
          this.$message.warning("输入信息不符合要求，请重新输入");
          return;
        }
        if (this.isEdit) {
          // console.log("isedmit");
          this.submitUpdate();
        } else {
          // console.log("!isedmit");
          this.submitAdd();
        }
      });
    },
    deleteCate(id, level) {
      this.$message.confirm("您确定要删除该分类数据吗").then(() => {
        // console.log(ret);
        console.log(id, level);
        this.$http
          .delete("/category", { params: { id, level } })
          .then((resp) => {
            if (!resp.flag) {
              this.$message.warning(resp.message);
              return;
            }
            this.getCateList();
          });
      });
    },
  },
};
</script>

<style lang='scss' scoped>
.tb-cate {
  margin: 15px 0;
}
.el-cascader {
  width: 100%;
}
</style>